let d = document;
let user = d.querySelector("header .user");

if (!isLogin()) {
  window.location.href = "login.html"
} else {
  let userC = `
    <span>用户：${sessionStorage.getItem("user_session")}</span>
    <span class="quit">退出</span>
  `;
  user.innerHTML += userC;
  if (!IsPC()) {
    user.querySelector(".quit").addEventListener("touchend", quitToLogin)
  } else {
    user.querySelector(".quit").addEventListener("click", quitToLogin)
  }
}

// canvas
let myCanvas = d.getElementById("my_canvas");
let w, h;

canvasSize();
window.addEventListener("resize", () => {
  canvasSize()
});
// 根据pc端和移动端指定canvas的区域大小
function canvasSize() {
  if (!IsPC()) {
    let bodyW = d.body.clientWidth;
    myCanvas.style.border = (bodyW % 10) / 2 + "px solid #606266";
    w = myCanvas.width = bodyW - (bodyW % 10);
    h = myCanvas.height = bodyW - (bodyW % 10);
  } else {
    let bodyW = d.body.clientWidth;
    myCanvas.style.border = 2 + "px solid #606266";
    w = myCanvas.width = 1000;
    h = myCanvas.height = 400;
  }
}







let cxt = myCanvas.getContext("2d");

// 指定蛇身体对应位置的数据
let snakeBody = [
  { x: 10, y: 10 },
  { x: 20, y: 10 },
  { x: 30, y: 10 }
];

// 食物位置数据，位置会通过方法随机生成
let food = { x: undefined, y: undefined };
let timer = null; // 定时器
let scoreD = d.querySelector(".unit .score .sum"); // 显示分数的元素
let score = 0; // 得分
let onOff = d.querySelector(".on_off"); // 开始按钮

const UP = 1; // 表示方向上
const DOWN = 2; // 下
const LEFT = 3; // 左
const RIGHT = 4; // 右
const EAT_OF_TRUE = true; // 表示吃到食物
const EAT_OF_FALSE = false; // 表示未吃到食物
const END_OF_TRUE = true; // 表示结束
const END_OF_FALSE = false; // 表示继续
let dir = RIGHT; // 指定对应方向


// 根据pc端和移动端给开始按钮绑定点击事件
bind();


function bind() {
  if (!IsPC()) {
    onOff.addEventListener("touchend", () => {
      onOff.classList.add("none");
      init()
    })
  } else {
    onOff.addEventListener("click", () => {
      onOff.classList.add("none");
      init()
    })
  }
}

// 初始化事件
function init() {
  scoreD.innerText = score;
  createBody(snakeBody);
  moveBody();
  createFood();
  toggleDir()
}

// 移动事件
function moveBody() {
  let temp;
  timer = setInterval(() => {
    clearBody(snakeBody);
    temp = snakeBody.shift();
    switch (dir) {
      case 1: temp = { x: snakeBody[snakeBody.length - 1].x, y: snakeBody[snakeBody.length - 1].y - 10 }; break;
      case 2: temp = { x: snakeBody[snakeBody.length - 1].x, y: snakeBody[snakeBody.length - 1].y + 10 }; break;
      case 3: temp = { x: snakeBody[snakeBody.length - 1].x - 10, y: snakeBody[snakeBody.length - 1].y }; break;
      case 4: temp = { x: snakeBody[snakeBody.length - 1].x + 10, y: snakeBody[snakeBody.length - 1].y }; break;
    }
    if (isEat(temp)) {
      snakeBody.unshift(snakeBody[0]);
      createFood()
    }
    if (isEnd(temp)) {
      clearInterval(timer);
      timer = null;
      let date = new Date();
      let data = {
        username: sessionStorage.getItem("user_session"),
        score: --score,
        ctime: (date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + date.getDate()).toString()
      }
      insert(data);
      stopGame();
      return
    }

    snakeBody.push(temp);
    createBody(snakeBody)
  }, 100)
}
// 生成身体
function createBody(bArr) {
  bArr.forEach(el => {
    cxt.beginPath();
    cxt.fillStyle = "#606266";
    cxt.fillRect(el.x, el.y, 10, 10)
  })
}

// 清楚身体
function clearBody(bArr) {
  bArr.forEach(el => {
    cxt.beginPath();
    cxt.clearRect(el.x - 1, el.y - 1, 12, 12)
  })
}
// 指定方法绑定事件，用于切换方向
function toggleDir() {
  document.onkeyup = e => {
    switch (e.which) {
      case 38: dir = UP; break;
      case 40: dir = DOWN; break;
      case 37: dir = LEFT; break;
      case 39: dir = RIGHT; break;
    }
  }

  let up = d.querySelector(".control .up");
  let down = d.querySelector(".control .down");
  let left = d.querySelector(".control .left");
  let right = d.querySelector(".control .right");
  up.addEventListener("touchstart", () => dir = UP);
  down.addEventListener("touchstart", () => dir = DOWN);
  left.addEventListener("touchstart", () => dir = LEFT);
  right.addEventListener("touchstart", () => dir = RIGHT);
}

// 生成食物
function createFood() {

  scoreD.innerText = score++;

  let x = parseInt(Math.random() * w);
  let y = parseInt(Math.random() * h);
  x -= (x % 10);
  y -= (y % 10);
  food = { x, y };
  cxt.beginPath();
  cxt.fillStyle = "red";
  cxt.fillRect(food.x, food.y, 10, 10)
}

// 判断是否吃到食物
function isEat(coor) {
  if (coor.x === food.x && coor.y === food.y)
    return EAT_OF_TRUE
  return EAT_OF_FALSE
}

// 判断是否结束
function isEnd(coor) {
  if (coor.x < 0 || coor.x >= w || coor.y < 0 || coor.y >= h)
    return END_OF_TRUE
  return END_OF_FALSE
}
// 停止游戏，初始化数据
function stopGame() {
  snakeBody = [
    { x: 10, y: 10 },
    { x: 20, y: 10 },
    { x: 30, y: 10 }
  ];
  score = 0;
  dir = RIGHT;
  cxt.beginPath();
  cxt.clearRect(0, 0, w, h);
  onOff.innerText = "再来亿次";
  onOff.classList.remove("none");
}